package zy.dao.order.impl;


import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.stereotype.Repository;

import zy.dao.BaseDaoImpl;
import zy.dao.order.WxOrderDAO;
import zy.dao.wx.product.WxProductDAO;
import zy.entity.sell.ecoupon.T_Sell_Ecoupon_User;
import zy.entity.wx.order.T_Wx_Order;
import zy.entity.wx.order.T_Wx_Order_Detail;
import zy.entity.wx.user.T_Wx_User;
import zy.entity.wx.user.T_Wx_User_Account_Detail;
import zy.util.Arith;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.IDUtil;
import zy.util.NumberUtil;
import zy.util.StringUtil;

@Repository
public class WxOrderDAOImpl extends BaseDaoImpl implements WxOrderDAO{
	@Resource
	private WxProductDAO wxProductDAO;
	@Override
	public List<T_Wx_Order> listOrder(Map<String, Object> paramMap) {
		StringBuffer sql = new StringBuffer();
		Object number= paramMap.get("number");
		String statustap= paramMap.get("statustap").toString();
		sql.append("SELECT id,number,sysdate,wu_code,shop_code,");
		sql.append(" amount,money,sell_money,");
		sql.append(" cd_money,state,companyid,cd_rate,");
		sql.append(" ec_money,wx_money,remark,order_status,pay_status,address,linkman,mobile");
		sql.append(" FROM t_wx_order t");
		sql.append(" WHERE 1=1");
		sql.append(" AND t.companyid=:companyid");
		sql.append(" AND t.wu_code=:wu_code");
		
		if (StringUtil.isNotEmpty(number)){
			sql.append(" AND t.number=:number");
		}
		if (StringUtil.isEmpty(statustap)){
			statustap="0";
		}
		//全部
		if ("0".equals(statustap)){
			//
		}
		//待付款
		else if ("1".equals(statustap)){
			sql.append(" AND t.order_status=0");
		}
		//待收货
		else if ("2".equals(statustap)){
			sql.append(" AND t.order_status=1");
		}
		//已收货
		else if ("3".equals(statustap)){
			sql.append(" AND t.order_status=2");
		}
		//已完成
		else if ("4".equals(statustap)){
			sql.append(" AND t.order_status=3");
		}
		//已售后
		else if ("5".equals(statustap)){
			sql.append(" AND t.order_status=4");
		}
		
		
		sql.append(" ORDER BY id DESC");
		sql.append(" LIMIT :start,:end");
		

		return namedParameterJdbcTemplate.query(sql.toString(),paramMap, 
				new BeanPropertyRowMapper<>(T_Wx_Order.class));
	}

	
	@Override
	public T_Wx_Order getOrder(Map<String, Object> paramMap) {
		StringBuffer sql = new StringBuffer();
		sql.setLength(0);
		sql.append(" SELECT ");
		sql.append(" number,sysdate,wx_money");
		sql.append(" FROM t_wx_order t");
		sql.append(" WHERE 1=1");
		sql.append(" AND number = :number");
		
		T_Wx_Order t_wx_order= namedParameterJdbcTemplate.queryForObject(sql.toString(), paramMap,
				new BeanPropertyRowMapper<>(T_Wx_Order.class));
		return t_wx_order;
	}
	@Override
	public int ModifyOrder(Map<String, Object> paramMap) {
		StringBuffer sql = new StringBuffer();
		sql.append(" UPDATE T_Wx_Order");
		sql.append(" SET order_status=:order_status,");
		sql.append(" pay_status=:pay_status,");
		sql.append(" trade_no=:trade_no");
		sql.append(" pay_time=:pay_time");
		sql.append(" WHERE id=:id");
		return namedParameterJdbcTemplate.update(sql.toString(), paramMap);
	}
	@Override
	public List<T_Wx_Order_Detail> getOrderDetail(Map<String, Object> paramMap) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT number,sysdate,pd_code,pd_name,");
		sql.append(" sub_code,sub_name,cr_code,cr_name,sz_code,sz_name,");
		sql.append(" br_code,br_name,amount,sell_price,price,");
		sql.append(" state,pd_pic,");
		sql.append(" companyid,wu_code");
		sql.append(" FROM t_wx_order_detail t");
		sql.append(" WHERE 1=1");
//		sql.append(" AND t.wu_code=:wu_code");
		sql.append(" AND t.number=:number");
//		sql.append(" AND t.companyid=:companyid");
		return namedParameterJdbcTemplate.query(sql.toString(), paramMap, 
				new BeanPropertyRowMapper<>(T_Wx_Order_Detail.class));
	}

	/**
	 * 确认收货
	 * @param paramMap
	 * */
	@Override
	public int confirmOrder(Map<String, Object> paramMap) {
		StringBuffer sql = new StringBuffer();
		sql.append(" UPDATE T_Wx_Order");
		sql.append(" SET order_status=2");
		sql.append(" WHERE 1=1 ");
		sql.append(" AND number = :number");
		return namedParameterJdbcTemplate.update(sql.toString(), paramMap);
	}
	/**
	 * 取消订单状态
	 * @param paramMap
	 * */
	@Override
	public int cancleOrder(Map<String, Object> paramMap) {
		StringBuffer sql = new StringBuffer();
		sql.append(" UPDATE T_Wx_Order");
		sql.append(" SET order_status=5");
		sql.append(" WHERE 1=1 ");
		sql.append(" AND number = :number");
		return namedParameterJdbcTemplate.update(sql.toString(), paramMap);
		
	}
	/**
	 * 保存订单数据
	 * 1.构造明细数据从购物车中取数据，构造订单明细数据
	 * 2.构造订单编号
	 * 3.验证库存
	 * 4.保存订单主表
	 * 5.保存订单明细表
	 * 6.返回状态值
	 * @param paramMap
	 * */
	@Override
	public Map<String, Object> saveOrder(Map<String, Object> paramMap) {
		try {
			StringBuffer sql = new StringBuffer();
			sql.append("SELECT ");
			sql.append(" sysdate,t.pd_code,t.pd_name,pd_pic,cr_name,sz_name,br_name,");
			sql.append(" sub_code,sub_name,cr_code,sz_code,br_code,amount,sell_price,price,t.companyid,t.wu_code,t.pd_pic");
			sql.append(" FROM t_wx_cartlist t");
			sql.append(" WHERE 1=1");
			sql.append(" AND id IN(:ids)");
			List<T_Wx_Order_Detail> order_Details = namedParameterJdbcTemplate.query(sql.toString(),paramMap,
					new BeanPropertyRowMapper<>(T_Wx_Order_Detail.class));
			if(null != order_Details && order_Details.size() > 0){
				int amount = 0;
				double money = 0d,sell_money = 0d;
				
				String number = IDUtil.buildId()+"";
				Date sysdate = DateUtil.getCurrentDate();
				String productdesc = "";
				for(T_Wx_Order_Detail detail:order_Details){
					amount += detail.getAmount();
					money += Arith.mul(detail.getPrice(), detail.getAmount());
					sell_money += Arith.mul(detail.getSell_price(), detail.getAmount());
					detail.setNumber(number);
					detail.setState(0);//零售
					detail.setSysdate(DateUtil.getCurrentDate());
					productdesc+=detail.getPd_name()+" ";
				}
				//TODO 未完待续
				double ec_money = NumberUtil.toDouble(paramMap.get("voucheramount"));
				double acc_money = NumberUtil.toDouble(paramMap.get("usedaccountamount"));
				double wx_money = money -ec_money -  acc_money;
				
				paramMap.put("number", number);
				paramMap.put("sysdate", sysdate);
				paramMap.put("amount", amount);
				paramMap.put("money", money);
				paramMap.put("sell_money",sell_money);
				paramMap.put("ec_money", ec_money);
				paramMap.put("acc_money", acc_money);
				paramMap.put("wu_code", paramMap.get("wu_code"));
				paramMap.put("cd_money", 0);
				paramMap.put("cd_rate", 0);
				paramMap.put("state", 0);
				paramMap.put("wx_money", wx_money);
				paramMap.put("remark", paramMap.get("message"));				
				
				//判断当前应付金额
				String order_status="0";//待付款
				if (wx_money == 0d){
					order_status="1";//已付款
				}
				paramMap.put("order_status", order_status);
				
				sql.setLength(0);
				sql.append(" INSERT INTO t_wx_order(");
				sql.append(" number,sysdate,wu_code,shop_code,");
				sql.append(" amount,money,sell_money,");
				sql.append(" cd_money,state,companyid,cd_rate,address,linkman,mobile,");
				sql.append(" ec_money,wx_money,remark,order_status");
				sql.append(" )VALUES(");
				sql.append(" :number,:sysdate,:wu_code,:shop_code,");
				sql.append(" :amount,:money,:sell_money,");
				sql.append(" :cd_money,:state,:companyid,:cd_rate,:address,:linkman,:mobile,");
				sql.append(" :ec_money,:wx_money,:remark,:order_status");
				sql.append(")");
				namedParameterJdbcTemplate.update(sql.toString(), paramMap);
				
				sql.setLength(0);
				sql.append(" INSERT INTO t_wx_order_detail(");
				sql.append(" number,sysdate,pd_code,pd_name,");
				sql.append(" sub_code,sub_name,cr_code,cr_name,sz_code,sz_name,");
				sql.append(" br_code,br_name,amount,sell_price,price,");
				sql.append(" state,companyid,pd_pic");
				sql.append(" )VALUES(");
				sql.append(" :number,:sysdate,:pd_code,:pd_name,");
				sql.append(" :sub_code,:sub_name,:cr_code,:cr_name,:sz_code,:sz_name,");
				sql.append(" :br_code,:br_name,:amount,:sell_price,:price,");
				sql.append(" :state,:companyid,:pd_pic");
				sql.append(")");
				namedParameterJdbcTemplate.batchUpdate(sql.toString(), SqlParameterSourceUtils.createBatch(order_Details.toArray()));
				
				sql.setLength(0);
				sql.append("DELETE FROM t_wx_cartlist");
				sql.append(" WHERE 1=1");
				sql.append(" AND id IN(:ids)");
				namedParameterJdbcTemplate.update(sql.toString(), paramMap);
				
				
				
				sql.setLength(0);
				sql.append(" SELECT ");
				sql.append(" number,sysdate,wu_code,shop_code,");
				sql.append(" amount,money,sell_money,");
				sql.append(" cd_money,state,companyid,cd_rate,address,linkman,mobile,");
				sql.append(" ec_money,wx_money,remark,order_status");
				sql.append(" FROM t_wx_order t");
				sql.append(" WHERE 1=1");
				sql.append(" AND number = :number");
				
				T_Wx_Order t_wx_order= namedParameterJdbcTemplate.queryForObject(sql.toString(), new MapSqlParameterSource().addValue("number", (Object)number),
						new BeanPropertyRowMapper<>(T_Wx_Order.class));
				
				//存在优惠券 变更使用状态
				if (ec_money !=0){
					//获取使用的优惠券CODE  更新当前使用的优惠券的关联订单编号和更新使用状态
					String voucherid = StringUtil.trimString(paramMap.get("voucherid"));
					
					sql.setLength(0);
					sql.append(" SELECT * ");
					sql.append(" FROM t_sell_ecoupon_user t");
					sql.append(" WHERE 1=1");
					sql.append(" AND ecu_id = :ecu_id");
					
					T_Sell_Ecoupon_User t_sell_ecoupon_user= namedParameterJdbcTemplate.queryForObject(sql.toString(), new MapSqlParameterSource().addValue("ecu_id", voucherid),
							new BeanPropertyRowMapper<>(T_Sell_Ecoupon_User.class));
					
					if (t_sell_ecoupon_user != null){
						t_sell_ecoupon_user.setEcu_state(1);//已使用
						t_sell_ecoupon_user.setEcu_ec_number(t_wx_order.getNumber());//关联订单号
						t_sell_ecoupon_user.setEcu_use_date(DateUtil.getCurrentTime());
						t_sell_ecoupon_user.setEcu_use_type(2);//微商城
						sql = new StringBuffer("");
						sql.append(" UPDATE t_sell_ecoupon_user SET ecu_state= :ecu_state, ecu_ec_number = :ecu_ec_number, ecu_use_date = :ecu_use_date, ecu_use_type = :ecu_use_type");
						sql.append(" WHERE ecu_id=:ecu_id");
						namedParameterJdbcTemplate.update(sql.toString(), new BeanPropertySqlParameterSource(t_sell_ecoupon_user));
					
					}
				}
				
				//存在账户抵扣 变更使用状态
				if (acc_money !=0){
					//更新t_wx_user主表 使用金额和剩余金额					
					sql.setLength(0);
					sql.append(" SELECT * ");
					sql.append(" FROM t_wx_user t");
					sql.append(" WHERE 1=1");
					sql.append(" AND wu_code = :wu_code");
					
					T_Wx_User t_wx_user= namedParameterJdbcTemplate.queryForObject(sql.toString(), new MapSqlParameterSource().addValue("wu_code", t_wx_order.getWu_code()),
							new BeanPropertyRowMapper<>(T_Wx_User.class));
					
					if (t_wx_user != null){
						t_wx_user.setWu_usedmoney(t_wx_user.getWu_usedmoney()+acc_money);//使用的
						t_wx_user.setWu_balance(t_wx_user.getWu_balance()-acc_money);//余额
						
						
						sql.setLength(0);
						sql.append(" UPDATE t_wx_user ");
						sql.append(" SET wd_state = 0 ");
						sql.append(" WHERE wd_user_code=:wu_code");
						namedParameterJdbcTemplate.update(sql.toString(), new MapSqlParameterSource().addValue("wu_usedmoney", t_wx_user.getWu_usedmoney()).addValue("wu_balance", t_wx_user.getWu_balance()));
						
//						sql = new StringBuffer("");
//						sql.append(" UPDATE t_wx_user ");
//						sql.append(" SET wd_state = 0 ");
//						sql.append(" WHERE wd_user_code=:wu_code");
//						namedParameterJdbcTemplate.update(sql.toString(), new BeanPropertySqlParameterSource(t_wx_user));
					
						//更新t_wx_user_account_detail明细 关联订单编号和更新使用状态
						paramMap = new HashMap<String,Object>();
						paramMap.put("type", "消费");
						paramMap.put("money", -acc_money);
						paramMap.put("wu_code", t_wx_order.getWu_code());
						paramMap.put("createdate", DateUtil.getCurrentDate());
						paramMap.put("remark", "订单消费抵扣："+acc_money);
						paramMap.put("order_number", t_wx_order.getNumber());
						sql.setLength(0);
						sql.append(" INSERT INTO t_wx_user_account_detail(");
						sql.append(" type,money,wu_code,createdate,remark,order_number");
						sql.append(" )VALUES(");
						sql.append(" :type,:money,:wu_code,:createdate,:remark,:order_number");
						sql.append(")");
						namedParameterJdbcTemplate.update(sql.toString(), paramMap);
						
					}
				}
				HashMap<String,Object> map = new HashMap<String,Object>();
				map.put("ordernumber", t_wx_order.getNumber());
				map.put("createdate", t_wx_order.getSysdate());
				map.put("paymoney", t_wx_order.getWx_money());
				map.put("productdesc", productdesc);
				map.put("orderstatus", t_wx_order.getOrder_status());
				
				return map;
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalArgumentException(e.toString());
		}
		return null;
	}
	
}
